<template>
  <view class="upload">
    <view class="empty-block" v-if="urlList.length == 0">
      <ve-image src="empty" class="empty_img" width="64" height="64" />
      <p class="empty_text">暂无数据</p>
    </view>
    <view class="list-item list-item-image preview-wrap" v-for="(item, index) in fileList" :key="index">
      <image v-if="item.waitFetching" :src="item.url" class="preview-image" mode="widthFix" @click="previewImg(index)"></image>
      <image
        v-else
        :src="item.url"
        class="preview-image"
        mode="aspectFill"
        @click="previewImg(index)"
        @load="onImgComplete(index)"
        @error="onImgComplete(index)"
      ></image>
    </view>
  </view>
</template>

<script setup>
  import { ref, watch } from 'vue'
  const props = defineProps({
    urlList: {
      type: Array,
      default: () => [],
    },
  })

  // 文件集合
  const fileList = ref([])
  // 图片加载完成
  const onImgComplete = (index) => {
    loadNextImg(index + 1)
  }
  const loadNextImg = (index = 0) => {
    if (index >= fileList.value.length) return
    const img = fileList.value[index]
    // 图片src赋值
    img.url = img['data-url']
    img.waitFetching = false
  }

  watch(
    () => props.urlList,
    (value) => {
      if (value && value.length > 0) {
        fileList.value = value.map((url) => {
          return {
            url: '/static/images/img-loading.png',
            'data-url': url,
            waitFetching: true,
          }
        })

        loadNextImg()
      }
    },
    { immediate: true },
  )
  const previewImg = (index) => {
    uni.previewImage({
      current: index,
      urls: props.urlList,
    })
  }
</script>

<style lang="less" scoped>
  .upload {
    // margin: 20rpx 0;
    display: flex;
    flex-wrap: wrap;
    align-items: center;
    .list-item {
      width: 204rpx;
      height: 204rpx;
      margin-right: 20rpx;
      overflow: hidden;
      // background: rgb(244, 245, 246);
      border-radius: 8rpx;
      border: 2rpx dashed #e2e2e2;
      overflow: hidden;
      position: relative;
      border-radius: 4rpx;
      /* #ifndef APP-NVUE */
      display: flex;
      /* #endif */
      align-items: center;
      justify-content: center;
      margin-bottom: 10rpx;
    }
    .list-item-image:nth-child(3n) {
      margin-right: 0;
    }
    .preview-wrap {
      border: 1px solid rgb(235, 236, 238);
    }
  }

  .empty-block {
    padding-top: 52rpx;
    text-align: center;
    width: 204rpx;
    height: 204rpx;
    background: #f2f3f5;
    border-radius: 4rpx 4rpx 4rpx 4rpx;
    border: 1px solid #e2e2e2;
    // 字
    font-size: 24rpx;
    font-weight: 400;
    color: #b6b6b6;
    line-height: 40rpx;
  }
</style>
